/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.aksw.treelearning.evaluation;
import org.aksw.treelearning.data.Mapping;

/**
 * Computes the precision, recall and F-score of mappings as computed by LIMES
 * @author ngonga
 */
public class PRFComputer {

    /** Computes the intersection between two mappings, used for computing true 
     * positives
     * @param m Input mapping
     * @param reference Reference mapping
     * @return The size of the intersection of the two mappings
     */ 
    public double getOverlap(Mapping m, Mapping reference)
    {
        double counter = 0;
        for(String key: m.map.keySet())
        {
            for(String value : m.map.get(key).keySet())
            {
                if(reference.map.containsKey(key))
                {
                    if(reference.map.get(key).containsKey(value))
                    {
                        counter++;
                    }
                }
            }
        }
        return counter;
    }

    /**
     * Computes the precision of the mapping m with respect to the reference mapping
     * @param m
     * @param reference
     * @return Precision
     */
    public double computePrecision(Mapping m, Mapping reference)
    {
        return getOverlap(m, reference)/(double)m.size();
    }

    /**
     * Computes the recall of the mapping m with respect to the reference mapping
     * @param m
     * @param reference
     * @return Recall
     */
    public double computeRecall(Mapping m, Mapping reference)
    {
        return getOverlap(m, reference)/(double)reference.size();
    }

    /**
     * Computes the F1-score of the mapping m with respect to the reference mapping
     * @param m
     * @param reference
     * @return F1-score
     */
    public double computeFScore(Mapping m, Mapping reference)
    {
        double overlap = getOverlap(m, reference);
        return 2*(overlap/(double)m.size())*(overlap/(double)reference.size())/((overlap/(double)m.size())+(overlap/(double)reference.size()));
    }
   
    public void testComputeFScore() {
    	Mapping m1 = new Mapping();
    	Mapping ref = new Mapping();
    	m1.add("a", "b", 1d);
    	ref.add("a", "b", 1d);
    	m1.add("a", "c", 2d);
    	PRFComputer prf = new PRFComputer();
    	double val = prf.computeFScore(m1, ref);
    	System.out.println(val);
    }
}
